<?php
/**
 * @package PWE.bdd
 * @author Gmax <gmaxfr78@gmail.com>
 */
class bdd_sql{
    public static $CONNECTION = null;
    public static $LASTERROR;
    
    private static $_PDO_MODE = true;
    
    private static $_serveur;
    private static $_dbname;
    private static $_username;
    private static $_password;

    public static function setServer($conf){
        self::$_serveur = $conf['server'];
        self::$_dbname = $conf['database_name'];
        self::$_username = $conf['username'];
        self::$_password = $conf['password'];
        
        // test compatibilite PDO_MYSQL
        if (!defined('PDO::ATTR_DRIVER_NAME')) {
            self::$_PDO_MODE = false;
        }
    }
    
    /**
     * retourne le resultat de la requete sql dans un tableau
     * 'count' nombre de ligne retournées
     * 'results'    $fetch==true => tableau des resultats 'fetcher'
     *              $fetch==false => resultat brut  
     * @param string $sql
     * @param boolean $fetch
     * @return array
     */
    public static function open(){
        $retour = true;
        if(self::$_PDO_MODE){
            $retour = self::open_pdo();
        }else{
            if( self::$CONNECTION === null ){
                try{
                    self::$CONNECTION = mysql_connect(self::$_serveur, self::$_username, self::$_password);
                    if(self::$CONNECTION===false) throw new Exception('connection impossible');
                    if(!mysql_select_db(self::$_dbname, self::$CONNECTION)) throw new Exception('base de donnée introuvable : '.self::$_dbname);
                }catch(Exception $e){
                    self::$CONNECTION = null;
                    self::$LASTERROR = $e->getMessage();
                    $retour = false;
                }
            }
        }
        return $retour;
    }
    public static function open_pdo(){
        if( self::$CONNECTION === null ){
            $dns = 'mysql:host='.self::$_serveur.';dbname='.self::$_dbname.';charset=UTF8';
            try {
                self::$CONNECTION = new PDO($dns,self::$_username,self::$_password);
            } catch (PDOException $e) {
                self::$LASTERROR = $e->getMessage();
                self::$CONNECTION = null;
            }
        }
        return (self::$CONNECTION!==null)?true:false;
    }
    
    /**
     * test la connectibilité au serveur, renvoi un tableau
     * [success(boolean),error(string),connect(PDO|int),pdo(boolean)]
     * @param string $server
     * @param string $user
     * @param string $password
     * @return array
     */
    public static function testConnexion($server,$user,$password,$dbname){
        ini_set('display_errors', FALSE);
        ini_set('display_startup_errors', FALSE);
        
        $pdoMode = (!defined('PDO::ATTR_DRIVER_NAME'))?false:true;
        $msg = 'Connexion au serveur impossible';
        $connexion = null;
        
        if($pdoMode){
            $dns = 'mysql:host='.$server.';dbname='.$dbname.';charset=UTF8';
            try {
                $connexion = new PDO($dns,$user,$password);
                if($connexion){
                    $retour = true;
                    $msg = 'Connexion au serveur établie';
                }
            } catch (PDOException $e) {
                switch($e->getCode()){
                    case 1049:{
                        $retour = true;
                        $msg = 'Connexion au serveur établie';
                        break;
                    }
                    default:{
                        $retour = false;
                    }
                }
            }
        }else{
            $connexion = mysql_connect($server, $user, $password);
            if($connexion===false){
                $retour = false;
            }else{
                $retour = true;
                $msg = 'Connexion au serveur établie';
            }
        }
        return array('success'=>$retour,'msg'=>$msg,'connect'=>$connexion,'pdo'=>$pdoMode);
    }
    /**
     * installation de la base de données via sql $tableConfig
     * @param string $server
     * @param string $user
     * @param string $password
     * @param string $dbname
     * @param string $tableConfig
     * @return array
     */
    public static function installDataBase($server,$user,$password,$dbname,$tableConfig){
        $pdoMode = (!defined('PDO::ATTR_DRIVER_NAME'))?false:true;
        $retour = true;
        if($pdoMode){
            $dns = 'mysql:host='.$server.';dbname='.$dbname.';charset=UTF8';
            try {
                $connexion = new PDO($dns,$user,$password);
                if($connexion){
                    $connexion->query($tableConfig);
                }else{
                    $retour = false;
                }
            } catch (PDOException $e) {
                $retour = false;
            }
        }else{
            $connexion = mysql_connect($server, $user, $password);
            if($connexion===false){
                $retour = false;
            }else{
                $retour = true;
                mysql_query($tableConfig,$connexion);
            }
        }
        return array('success'=>$retour,'msg'=>'');
    }
    /**
     * fermeture de la connexion sql
     */
    public static function close(){
        if(self::$_PDO_MODE && is_a(self::$CONNECTION, 'PDO')){
            self::$CONNECTION = null;
        }elseif(self::$CONNECTION!==null){
            mysql_close(self::$CONNECTION);
            self::$CONNECTION = null;
        }
        
    }
    
    /**
     * renvoi le tableau de résultat pour la requête $sql 
     * @param string $sql : query sql à executer
     * @param boolean $fetch : true pour renvoyer les lignes de résultat en tableau
     * @param boolean $assoc : true pour retourner les lignes en tableau associatif uniquement
     * @return array : [count: nombre de ligne de resultat, results: array des lignes de résultat|résultat brut]
     */
    public static function doSql($sql,$fetch=true,$assoc=false){
        if(self::$_PDO_MODE){
            $retour = self::doSql_pdo($sql,$fetch,$assoc);
        }else{
            $retour = array('count'=>0,'results'=>array(),'query'=>$sql);
            if(self::open()){
                $result = @mysql_query($sql,self::$CONNECTION);

                if(mysql_error(self::$CONNECTION)!='') self::$LASTERROR = mysql_error(self::$CONNECTION);

                $retour['count'] = @mysql_affected_rows(self::$CONNECTION);
                if($fetch){
                    $results = array();
                    if($assoc){
                        while($data = @mysql_fetch_assoc($result)){
                            $results[] = $data;
                        }
                    }else{
                        while($data = @mysql_fetch_array($result)){
                            $results[] = $data;
                        }
                    }

                    $retour['results'] = $results;
                }else{
                    $retour['results'] = $result;
                }
            }
            
        }
        return $retour;
    }
    public static function doSql_pdo($sql,$fetch=true,$assoc=false){
        $retour = array('count'=>0,'results'=>array(),'query'=>$sql);
        if(self::open()){
            try{
                $result = self::$CONNECTION->query($sql);
            } catch (PDOException $e){
                self::$LASTERROR = $e->getMessage();
            }
            if($result){
                $retour['count'] = $result->rowCount();
                if($fetch){
                    if($assoc){
                        $result->setFetchMode(PDO::FETCH_ASSOC);
                    }
                    $retour['results'] = $result->fetchAll();
                    $retour['count'] = count($retour['results']);
                }
            }
        }
        return $retour;
    }
        
    public static function changePrefixTable($newPrefix,$oldPrefix=''){
        $sql = 'SHOW TABLES FROM '.self::$_dbname;
        $liste = self::doSql($sql);
        foreach ($liste['results'] as $table_name){
            $oldName = $table_name[0];
            $baseName = str_replace($oldPrefix, '', $oldName);
            $newName = $newPrefix.$baseName;
            $renameSql = 'RENAME TABLE `'.self::$_dbname.'`.`'.$oldName.'` TO `'.self::$_dbname.'`.`'.$newName.'`';
            self::doSql($renameSql);
        }
        $retour = true;
        $listeVerif = self::doSql($sql);
        foreach ($listeVerif['results'] as $table_name){
            $name = $table_name[0];
            $baseName = str_replace($newPrefix, '', $name);
            if($newPrefix.$baseName !== $name){
                $retour = false;
            }
        }
        return $retour;
    }
    
    /**
     * retourne la valeur du dernier identifiant autoincrémenté
     * @return int
     */
    public static function getLastInsertId(){
        if(self::$_PDO_MODE && is_a(self::$CONNECTION, 'PDO')){
            return self::$CONNECTION->lastInsertId();
        }else{
            return mysql_insert_id(self::$CONNECTION);
        }
    }
}
?>